package me.liuyu2783.dubbo.sample.http;

import com.alibaba.fastjson.JSON;
import me.liuyu2783.dubbo.sample.dubbo.Invocation;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * me.liuyu2783.dubbo.sample.tomcat
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class HttpClient {


    public String send(String host, int port, Invocation invocation){
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://"+host+":"+port);
        String result = "";
        try {
            StringEntity s = new StringEntity(JSON.toJSONString(invocation));
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                // 返回json格式：
                System.out.println("-----------");
                result = EntityUtils.toString(res.getEntity());
            }
            System.out.println("++++++++++++++");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
